package cn.green.captcha.filter;

import cn.green.captcha.exception.VerificationCodeException;
import cn.green.captcha.handler.DefaultCaptchaFailureHandler;
import cn.green.utils.StringUtils;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * 定义图形码验证过滤器
 */
public class VerificationCodeFilter extends OncePerRequestFilter {

    //权限验证失败处理器
    private DefaultCaptchaFailureHandler handler = new DefaultCaptchaFailureHandler();

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain)
            throws ServletException, IOException {
        //如果不是登录uri，则不进行处理
        if (!"/doLogin".equals(httpServletRequest.getRequestURI())) {
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        } else {
            try {
                this.verificationCode(httpServletRequest);
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            } catch (VerificationCodeException e) {
                handler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            }
        }
    }

    /**
     * 校验验证码
     */
    private void verificationCode(HttpServletRequest request) throws VerificationCodeException
    {
        //获取用户输入的验证码
        String captcha = request.getParameter("captcha");
        //获取用户会话
        HttpSession session = request.getSession();
        //获取会话中的正确的验证码
        String targetCaptcha = (String) session.getAttribute("captcha");

        //清除会话中的验证码
        if (StringUtils.isNotEmpty(targetCaptcha)) {
            session.removeAttribute("captcha");
        }

        //开始校验验证码
        if (StringUtils.isEmpty(captcha) ||
            StringUtils.isEmpty(targetCaptcha) ||
            !targetCaptcha.equals(captcha)) {
            throw new VerificationCodeException();
        }
    }
}
